延續昨天的專案,這邊定義了一個BluetoothServices的擴充,並使用CBPeripheralDelegate協議。
以下程式是發現服務時執行,需要注意的點是這邊指的服務是全部的服務,一個裝置裡面有很多服務
extension BluetoothServices: CBPeripheralDelegate {
// 發現服務
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if let service = peripheral.services {
for service in service {
print(service)
peripheral.discoverCharacteristics(nil, for: service)
}
}
}
特徵始終是服務的一部分,它代表服務器要向客戶端公開的一條信息/數據。該特徵包含有助於定義其擁有的值的其他屬性
這邊先說明一下為甚麼會使用到uuid,因為在藍芽GATT層中,所有的屬性都有定義一個uuid值,這邊是如果uuid == FFE1的話,讀取其特徵的值,並設定通知值,如果為true,表示可以接收通知或是指示,並把特徵值儲存在rxtxCHaracteristic
// 發現對應服務的特徵
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let characteristics = service.characteristics {
for characteristic in characteristics {
print(characteristic)
if characteristic.uuid.isEqual(CBUUID(string: "FFE1")){
peripheral.readValue(for: characteristic)
peripheral.setNotifyValue(true, for: characteristic)
rxtxCHaracteristic = characteristic
}
}
}
}
// 特徵值變更
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard characteristic == rxtxCHaracteristic,
let characteristicValue = characteristic.value,
let ASCIIstring = String(data: characteristicValue,
encoding: String.Encoding.utf8)
else {
return
}
print(ASCIIstring)
delegate?.getBLEPeripheralValue(value: ASCIIstring)
}
}
這邊是昨天有介紹到的回傳藍芽狀態的程式喔!
extension BluetoothServices: CBPeripheralManagerDelegate {
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
switch peripheral.state{
case .unknown:
print("unknown")
case .resetting:
print("resetting")
case .unsupported:
print("unsupported")
case .unauthorized:
print("unauthorized")
case .poweredOff:
print("poweredOff")
case .poweredOn:
print("poweredOn")
@unknown default:
print("藍芽裝置未知狀態")
}
}
}
這邊宣告了BluetoothServiceDelegate的協議,這其中包含了兩個func
protocol BluetoothServiceDelegate: NSObjectProtocol {
func getBLEPeripherals(peripherals: [CBPeripheral])
func getBLEPeripheralValue(value: String)
}
經過今天的分享,是不是覺得有看沒有懂呢?沒關係,大家可以參考底下的連結喔,先了解定義,再回來看程式碼會更清楚喔!明天我們將完成這個專案囉!